package com.study.daily.algozuo.y2021.m12.day1209;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2021/12/9 下午 06:59
 * @version: 1.0
 */
public class Code02_CardInLine_C18 {
    public static void main(String[] args) {
        int[] arr = { 5, 7, 4, 5, 8, 1, 6, 0, 3, 4, 6, 1, 7 };
        System.out.println(whoWin1(arr));
        System.out.println(whoWin2(arr));
        System.out.println(whoWin3(arr));
    }
    public static int whoWin1(int[] arr) {
        int L = 0, R = arr.length - 1;
        int first = f1(arr, L, R);
        int last = g1(arr, L, R);
        return Math.max(first, last);
    }

    public static int f1(int[] arr, int L, int R) {
        if (L == R) {
            return arr[L];
        }
        int p1 = arr[L] + g1(arr, L + 1, R);
        int p2 = arr[R] + g1(arr, L, R - 1);
        return Math.max(p1, p2);
    }

    public static int g1(int[] arr, int L, int R) {
        if (L == R) {
            return arr[L];
        }
        int p1 = arr[L] + f1(arr, L + 1, R);
        int p2 = arr[R] + f1(arr, L, R - 1);
        return Math.min(p1, p2);
    }

    public static int whoWin2(int[] arr){
        int L = 0, R = arr.length - 1;
        int [][] fdp = new int[arr.length][arr.length];
        int [][] gdp = new int[arr.length][arr.length];
        for (int i = 0; i <= R; i++){
            for(int j = 0; j <= R; j++){
                fdp[i][j] = -1;
                gdp[i][j] = -1;
            }
        }
        int first = f2(arr, L, R, fdp);
        int last = g2(arr, L, R, gdp);
        return Math.max(first, last);
    }

    public static int f2(int[] arr, int L, int R, int[][] fdp) {
        if(fdp[L][R] != -1){
            return fdp[L][R];
        }
        if (L == R) {
            fdp[L][R] = arr[L];
            return arr[L];
        }
        int p1 = arr[L] + g2(arr, L + 1, R, fdp);
        int p2 = arr[R] + g2(arr, L, R - 1, fdp);
        fdp[L][R] = Math.max(p1, p2);
        return Math.max(p1, p2);
    }

    public static int g2(int[] arr, int L, int R, int[][] gdp) {
        if(gdp[L][R] != -1){
            return gdp[L][R];
        }
        if (L == R) {
            gdp[L][R] = arr[L];
            return arr[L];
        }
        int p1 = arr[L] + f2(arr, L + 1, R, gdp);
        int p2 = arr[R] + f2(arr, L, R - 1, gdp);
        gdp[L][R] = Math.min(p1, p2);
        return Math.min(p1, p2);
    }

    public static int whoWin3(int[] arr){
        int N = arr.length - 1;
        int[][] fmap = new int[N+1][N+1];
        int[][] gmap = new int[N+1][N+1];
        for(int i = 0; i <= N;i++){
            fmap[i][i] = arr[i];
            gmap[i][i] = arr[i];
        }
        for(int i = N - 1; i >= 0; i--){
            for(int j = i + 1; j <= N; j++){
                fmap[i][j] = Math.max(arr[i] + gmap[i+1][j], arr[j] + gmap[i][j-1]);
                gmap[i][j] = Math.min(arr[i] + fmap[i+1][j], arr[j] + fmap[i][j-1]);
            }
        }
        return Math.max(fmap[0][N], gmap[0][N]);
    }
}
